(function(App) {
    'use strict';
    var querystring = require('querystring');
    var request = require('request');
    var Q = require('q');
    var http = require('http');
    zlib = require('zlib');
    var cheerio = require('cheerio');
    var magnetLink = '';

    var URL = false;
    var Kickxxx = function() {
    };

    Kickxxx.prototype.constructor = Kickxxx;

    var queryTorrents = function(filters) {

        var deferred = Q.defer();

        var params = {};
        params.field = 'seeders';
        params.sorder = 'desc';

        if (filters.sorder) {
            var sorder = 'desc';
            if (filters.sorder === 1) {
                sorder = 'asc';
            }
            params.sorder = sorder;
        }

        var url = AdvSettings.get('kickxxxApiEndpoint') + 'json.php?q=category:video-xxx&' + querystring.stringify(params).replace(/%E2%80%99/g, '%27');

        win.info('Request to KICKXXX API');
        win.debug(url);
        request({url: url, json: true}, function(error, response, data) {
            if (error) {
                deferred.reject(error);
            } else if (!data || (data.error && data.error !== 'No movies found')) {
                var err = data ? data.error : 'No data returned';
                win.error('KICKXXX error:', err);
                deferred.reject(err);
            } else {
                deferred.resolve(data.list || []);
            }
        });

        return deferred.promise;
    };


    var formatForPopcorn = function(items) {
        var results = {};
        var movieFetch = {};
        movieFetch.results = [];
        movieFetch.hasMore = (items.length === 50 ? true : false);
        _.each(items, function(movie) {
            var imdb = movie.hash;

            // Calc torrent health
            var seeds = movie.seeds;
            var peers = movie.peers;
            console.log(movie.link);

            http.get(movie.link, function(res) {
                var body = '';

                var output;
                if (res.headers['content-encoding'] === 'gzip') {
                    var gzip = zlib.createGunzip();
                    res.pipe(gzip);
                    output = gzip;
                } else {
                    output = res;
                }

                output.on('data', function(data) {
                    body += data;
                });

                output.on('end', function() {
                    var $ = cheerio.load(body);
                    $(".magnetlinkButton").each(function() {
                        var link = $(this);
                        magnetLink = link.attr("href");
                    });
                    console.log(magnetLink);
                });
            });

            var torrents = {};
            torrents[movie.Quality] = {
                url: magnetLink,
                size: movie.size,
                seed: seeds,
                peer: peers
            };

            var ptItem = results[imdb];
            if (!ptItem) {
                ptItem = {
                    imdb: imdb,
                    title: movie.Title,
                    year: movie.pubDate,
                    rating: movie.votes,
                    torrents: torrents
                };

                movieFetch.results.push(ptItem);
            } else {
                _.extend(ptItem.torrents, torrents);
            }

            results[imdb] = ptItem;
        });
        return movieFetch;
    };

    Kickxxx.prototype.extractIds = function(items) {
        return _.pluck(items.results, 'imdb');
    };

    Kickxxx.prototype.fetch = function(filters) {
        return queryTorrents(filters)
                .then(formatForPopcorn);
    };

    App.Providers.Kickxxx = Kickxxx;

})(window.App);
